<?php

namespace App\Http\Controllers\addresscontroller;

use App\Exceptions\BusinessException;
use App\Http\Controllers\Controller;
use App\Models\Address;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Pojo\Response;
use Log;
class AddressController extends Controller
{
    /**
     * 获取地址列表
     */
    public function addressList(Request $request){
        
        $request->validate([
            'page' => 'required|integer',
            'pageSize' => 'required|integer',
        ]);
        
        $addresses = Address::where('user_id', Auth::id())
            ->where('deleted_at', null)
            ->orderBy('created_at', 'desc')
            ->paginate($request->pageSize, ['*'], 'page', $request->page);
            
        return response()->json([
            'code' => 200,
            'data' => [
                'list' => $addresses->items(),
                'total' => $addresses->total(),
                'current_page' => $addresses->currentPage(),
                'per_page' => $addresses->perPage(),
                'last_page' => $addresses->lastPage()
            ]
        ]);
    }

    /** 
     * 保存地址
     */
    public function addressSave(Request $request){
        
        $request->validate([
            'address' => 'required|string',
            'describe' => 'nullable|string',
        ]);
        
        $address = new Address();
        $address->address = $request->address;
        $address->describe = $request->describe;
        $address->user_id = Auth::id();
        $address->save();
        
        return Response::success(null, '地址保存成功');
        
    }

    /**
     * 删除地址
     */
    public function deleteAddress(Request $request){
        
        $ids = $request->validate([
            'ids'=> 'required|array',
        ]);

        $addresses = Address::whereIn('id', $ids['ids'])
            ->where('user_id', Auth::id())
            ->get();
            
        foreach ($addresses as $address) {
            $address->deleted_at = now();
            $address->save();
        }
        

        return Response::success(null, '地址删除成功');

    }
}
